# -*- coding:utf-8 -*-

from __future__ import print_function

import argparse
import sys
import tempfile

from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
import lesson3.mnist_model as mnist_model
from PIL import Image,ImageFilter,ImageOps

def load_data(argv):
    grayimage = Image.open(argv).convert('L')
    width = float(grayimage.size[0])
    height = float(grayimage.size[1])
    print(width,height)
    newImage = Image.new('L', (28, 28), (255))
    if width > height:
        nheight = int(round((20.0 / width * height), 0))
        print("nheight:{0}".format(nheight))
        if (nheight == 0):
            nheight = 1
        img = grayimage.resize((20, nheight), Image.ANTIALIAS).filter(ImageFilter.SHARPEN)
        wtop = int(round(((28 - nheight) / 2), 0))
        newImage.paste(img, (4, wtop))
    else:
        nwidth = int(round((20.0 / height * width), 0))
        print("nwidth:{0}".format(nwidth))
        if (nwidth == 0):
            nwidth = 1
        img = grayimage.resize((nwidth, 20), Image.ANTIALIAS).filter(ImageFilter.SHARPEN)
        wleft = int(round(((28 - nwidth) / 2), 0))
        newImage.paste(img, (wleft, 4))

    newImage = ImageOps.invert(newImage)
    return list(newImage.getdata())



def main(argv):

    imvalue = load_data(argv)

    x = tf.placeholder(tf.float32, [None, 784])
    y_ = tf.placeholder(tf.float32, [None, 10])
    y_conv, keep_prob = mnist_model.deepnn(x)

    y_predict = tf.nn.softmax(y_conv)
    init_op = tf.global_variables_initializer()
    saver = tf.train.Saver()
    with tf.Session() as sess:
        sess.run(init_op)
        saver.restore(sess,  r"E:\testDir\ml\model\mnist\mnist_cnn_model.ckpt")
        prediction=tf.argmax(y_predict,1)
        predint = prediction.eval(feed_dict={x: [imvalue],keep_prob: 1.0}, session=sess)
        print (predint[0])

if __name__ == "__main__":
    main(r"E:\testDir\ml\trainData\test_num\2.png")